/*
三、基于下面提供的代码，完成后续的四个练习
// support.js
class Container {
    static of(value){
        return new Container(value)
    }
    constructor(value){
        this._value = value
    }
    map(fn){
        return Container.of(fn(this._value))
    }
}

class Maybe {
    static of(x){
        return new Maybe(x)
    }
    isNothing(){
        return this._value === null || this._value === undefined
    }
    constructor(x){
        this._value = x
    }
    map(fn){
        return this.isNothing() ? this : Maybe.of(fn(this._value))
    }
}
module.exports = { Maybe, Container }
 * */

const fp = require("lodash/fp");
const { Maybe, Container } = require("./support");
/*
练习1：使用 fp.add(x, y) 和 fp.map(f,x) 创建一个能让 functor 里的值增加的函数 ex1
const fp = require('lodash/fp')
const {Maybe, Container} = require('./support')
let maybe = Maybe.of([5,6,1])
let ex1 = () => {
	// 你需要实现的函数。。。
}
函子对象的 map 方法可以运行一个函数对值进行处理，函数的参数为传入 of 方法的参数；
接着对传入的整个数组进行遍历，并对每一项执行 fp.add 方法*/
let maybe = Maybe.of([5, 6, 1]);
let ex1 = (number) => maybe.map(fp.map(fp.add(number)));
console.log(ex1(2));

/*
练习2：实现一个函数 ex2，能够使用 fp.first 获取列表的第一个元素
const fp = require('lodash/fp')
const {Maybe, Container} = require('./support')
let xs = Container.of(['do', 'ray', 'me', 'fa', 'so', 'la', 'ti', 'do'])
let ex2 = () => {
    // 你需要实现的函数。。。
}
*/
let xs = Container.of(["do", "ray", "me", "fa", "so", "la", "ti", "do"]);
let ex2 = () => xs.map(fp.first);
console.log(ex2());

/*
练习3：实现一个函数 ex3，使用 safeProp 和 fp.first 找到 user 的名字的首字母
const fp = require('lodash/fp')
const {Maybe, Container} = require('./support')
let safeProp = fp.curry(function(x, o){
    return Maybe.of(o[x])
})
let user = { id: 2, name: 'Albert' }
let ex3 = () => {
    // 你需要实现的函数。。。
}
*/
let safeProp = fp.curry(function (x, o) {
  return Maybe.of(o[x]);
});
let user = { id: 2, name: "Albert" };
let ex3 = (user) => safeProp("name", user).map(fp.first);
console.log(ex3(user));

/*
练习4：使用 Maybe 重写 ex4，不要有 if 语句
const fp = require('lodash/fp')
const {Maybe, Container} = require('./support')
let ex4 = function(n){
    if(n){
        return parseInt(n)
    }
}
*/
let ex4 = function (n) {
  return Maybe.of(n).map(parseInt);
};
console.log(ex4(false));
